//
// Created by castle on 2020/9/10.
//

#include "Ai.h"

#define SCORE_1_01 (3)
#define SCORE_1_02 (2)
#define SCORE_2_01 (2)
#define SCORE_2_02 (3)
#define SCORE_1_11 (50)
#define SCORE_1_22 (40)
#define SCORE_2_11 (40)
#define SCORE_2_22 (50)

const uint8_t Ai::winWay[9][4][2] =
		{
				{{1, 2}, {3, 6}, {4, 8}},
				{{0, 2}, {4, 7}},
				{{0, 1}, {5, 8}, {4, 6}},
				{{0, 6}, {4, 5}},
				{{0, 8}, {1, 7}, {2, 6}, {3, 5}},
				{{3, 4}, {2, 8}},
				{{0, 3}, {2, 4}, {7, 8}},
				{{1, 4}, {6, 8}},
				{{0, 4}, {2, 5}, {6, 7}}
		};

const uint8_t Ai::winWayLen [9] = {3, 2, 3, 2, 4, 2, 3, 2, 3};

uint8_t Ai::PickNextCell(const uint8_t *cells, bool firstHand)
{
	int score[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
	int SCORE[3][3] = {0, 0, 0, 0, 0, 0, 0, 0, 0};

	SCORE[0][0] = 1;
	SCORE[1][2] = 0;
	if(firstHand)
	{
		SCORE[0][1] = SCORE_1_01;
		SCORE[0][2] = SCORE_1_02;
		SCORE[1][1] = SCORE_1_11;
		SCORE[2][2] = SCORE_1_22;
	}
	else
	{
		SCORE[0][1] = SCORE_2_01;
		SCORE[0][2] = SCORE_2_02;
		SCORE[1][1] = SCORE_2_11;
		SCORE[2][2] = SCORE_2_22;
	}
	for(int i = 0; i < 9; ++i)
	{
		if(cells[i] == 0)
		{
			for(int j = 0; j < winWayLen[i]; ++j)
			{
				int flag = cells[winWay[i][j][0]] + cells[winWay[i][j][1]];
				int flag2 = cells[winWay[i][j][0]] * cells[winWay[i][j][1]];
				if(flag == 0)
					score[i] += SCORE[0][0];
				if(flag == 1)
					score[i] += SCORE[0][1];
				if(flag == 2 && flag2 == 0)
					score[i] += SCORE[0][2];
				if(flag == 2 && flag2 == 1)
					score[i] += SCORE[1][1];
				if(flag == 3)
					score[i] += SCORE[1][2];
				if(flag == 4)
					score[i] += SCORE[2][2];
			}
		}
		else
			score[i] = -1;
	}
	int max_v = 0, max_i = 0;
	for(int i = 0; i < 9; i++)
	{
		if(score[i] > max_v)
		{
			max_v = score[i];
			max_i = i;
		}
	}
	return max_i;
}
